package com.shujiaotong.controller;


import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.shujiaotong.common.R;
import com.shujiaotong.pojo.Classes;
import com.shujiaotong.pojo.User;
import com.shujiaotong.pojo.UserCard;
import com.shujiaotong.pojo.UserClass;
import com.shujiaotong.service.IClassesService;
import com.shujiaotong.service.IUserCardService;
import com.shujiaotong.service.IUserClassService;
import com.shujiaotong.service.IUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author author
 * @since 2024-10-20
 */
@RestController
@Slf4j
@RequestMapping("/userClasses")
public class UserClassController {

    @Autowired
    private IClassesService classesService;

    @Autowired
    private IUserCardService userCardService;

    @Autowired
    private IUserService userService;

    @Autowired
    private IUserClassService userClassService;

//    会员选课业务
    @RequestMapping("chooseClasses")
    public R chooseClasses(@RequestBody Map<String,Long> map){
        log.info("会员选课业务：{}",map);

//        通过map接收classId和userId
        Long classId = map.get("classId");
        Long userId = map.get("userId");
//        查询课程信息
        Classes classes = classesService.getById(classId);
//        课程过期
        if(classes.getEndTime().isBefore(LocalDateTime.now())){
            return R.error("课程过期");
        }
//        课程人数已满
        if(classes.getPnum()>=classes.getPmax()){
            return R.error("课程人数已满，无法选择");
        }
//        获取用户的卡信息
        LambdaQueryWrapper<UserCard> qw = new LambdaQueryWrapper<>();
        qw.eq(UserCard::getUserId,userId);
        List<UserCard> userCardAll = userCardService.list(qw);
//        卡片过期、次数用尽、禁用、卡和课tags标签有关联
//        userCardOk
        List<UserCard> userCardOk = userCardAll.stream().filter(item -> {
//            1.过期
            return item.getEndDate().isAfter(LocalDate.now());
        }).filter(item -> {
//            2.次数卡 次数用尽
            boolean flag = false;
            if (item.getType().equals("期限卡")) {
                flag = true;
            }
            if (item.getType().equals("次卡")
                    && item.getCount() >= 1) {
                flag = true;
            }
            return flag;
        }).filter(item -> {
//            卡和标签的关系
            String _tagsCard = item.getTags();
            String _tagsClasses = classes.getTags();
//            撕裂
            String[] tagsCard = _tagsCard.split(",");
            String[] tagsClasses = _tagsClasses.split(",");
//            取交集
            Collection<String> intersection = CollectionUtil.intersection(
                    Arrays.asList(tagsCard), Arrays.asList(tagsClasses));
            return intersection != null && intersection.size() > 0 ? true : false;
        }).map(item -> {
//            处理业务，返回对象，用作收集
//            对可用卡做标识
            item.setDisabled(true);
            return item;
        }).toList();

//        可用卡集合排除异常情况
        if(StringUtils.isEmpty(userCardOk)||userCardOk.size()<=0){
            return R.error("没有可用卡，无法选择");
        }

//        自动业务
//        定义用户使用的卡
        UserCard thisUserCard = null;
        for (UserCard userCard : userCardOk) {
            if (userCard.getType().equals("期限卡")){
                thisUserCard = userCard;
                break;
            }
        }
//        没有期限卡，是否有次卡
        if (thisUserCard==null){
            for (UserCard userCard : userCardOk) {
                if (userCard.getType().equals("次卡")){
                    userCard.setCount(userCard.getCount()-1);
//                    卡片信息同步
                    userCardService.updateById(userCard);
                    thisUserCard = userCard;
                    break;
                }
            }
        }

//        查询用户信息
        User user = userService.getById(userId);
//        在用户课程中新增用户数据
        UserClass userClass = new UserClass();
        userClass.setUserId(userId);
        userClass.setClassId(classId);
        userClass.setUserName(user.getName());
        userClass.setClassName(classes.getName());
        userClass.setStatus(1);// 可用
        userClass.setCreateTime(LocalDateTime.now());
        userClass.setTags(classes.getTags());
        userClassService.save(userClass);
        return R.success(userCardOk);
    }


//    通过用户Id获取已选课程列表
    @GetMapping("{userId}")
    public R getClassesById(@PathVariable Long userId){
        LambdaQueryWrapper<UserClass> qw = new LambdaQueryWrapper<>();
        qw.eq(UserClass::getUserId,userId);
        return R.success(userClassService.list(qw));
    }

    @GetMapping("/getClassesTotalCount/{tid}")
    public R getClassesTotalCount(@PathVariable Long tid){
        long total = userClassService.getClassesTotalCount(tid);
        return R.success(total);
    }

    @GetMapping("/getMouthTotal/{tid}")
    public R getMouthTotal(@PathVariable Long tid){
        long total = userClassService.getMouthTotal(tid);
        return R.success(total);
    }

    @GetMapping("/getTheacherCount/{tid}")
    public R getTheacherCount(@PathVariable Long tid){
        Map<String,Long> map= userClassService.getTheacherCount(tid);
        return R.success(map);
    }

     //    根据课程id获取已选此课会员列表getClassesByUserId
    @GetMapping("getClassesByUserId/{classId}")
    public R getClassesByUserId(@PathVariable Long classId){
        LambdaQueryWrapper<UserClass> qw = new LambdaQueryWrapper<>();
        qw.eq(UserClass::getClassId,classId);
        List<UserClass> list = userClassService.list(qw);
        list.forEach(item->{
            item.setPhone(userService.getById(item.getUserId()).getPhone());
        });
        return R.success(list);
    }

//    attendance修改会员签到状态
    @PutMapping("/attendance")
    public R attendance(UserClass userClass){
        LambdaQueryWrapper<UserClass> lqw = new LambdaQueryWrapper<>();
        lqw.eq(UserClass::getClassId,userClass.getClassId());
        lqw.eq(UserClass::getId,userClass.getId());
        userClass.setStatus(userClass.getStatus());
        boolean update = userClassService.update(userClass, lqw);
        return update?R.success("成功"):R.error("失败");
    }

    @PostMapping
    public R add(@RequestBody Classes classes){
        return classesService.save(classes)?R.success("新增成功"):R.error("新增失败");
    }
}
